<template>
    <!--角色相关操作区开始-->
    <div class="card">
        <el-button type="primary" @click="handleAdd" style="margin: 0 20px">新增角色</el-button>
        <el-input :prefix-icon="Search" placeholder="请输入角色名"
                  v-model="data.role_name"
                  clearable
                  style="width: 240px; margin: 0 20px"/>
        <el-select
            v-model="authorityName"
            placeholder="请选择权限"
            clearable
            style="width: 240px"
        >
            <el-option
                v-for="item in options"
                :key="item.authorityName"
                :label="item.label"
                :value="item.authorityName"
            />
        </el-select>
        <el-button @click="reset" style="margin: 0 20px">重置</el-button>
        <el-button type="primary" @click="roleload" style="margin: 0 20px">查询</el-button>
    </div>
    <!--角色相关操作区结束-->

    <!-- 角色列表开始 -->
    <div class="card">
        <!-- el-table-column 的 template 标签中使用 #default="scope"，这是作用域插槽的写法，通过 scope 可以访问到当前行的数据对象 scope.row。 -->
        <el-table :data="data.tableData" style="width: 100%; min-height: 350px"
                  :header-cell-style="{ fontWeight: 'bold', color: '#1d1c1c', textAlign: 'center', backgroundColor: '#f5f4f1'}"
                  :cell-style="{ textAlign: 'center' }"
        >
            <el-table-column prop="roleName" label="角色名称" />
            <el-table-column prop="description" label="角色描述" />
            <el-table-column label="权限">
                <template #default="scope"> <!-- 作用域插槽 -->
                    <el-tag v-for="authority in scope.row.authorities" :key="authority.authorityId">
                        {{ authority.authorityName }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="80">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button link type="danger" size="small" @click="deleteRole(scope.row.roleId)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <!-- 角色列表结束 -->

    <!--数据分页功能区开始-->
    <div class="card">
        <el-pagination
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[5, 10, 20]"
            :total="data.total"
            @current-change="roleload"
            @size-change="roleload"
        />  <!--@current-change : 改变时触发，再次请求一次数据，实现分页查询;  @size-change: 数量改变触发-->
    </div>
    <!--数据分页功能区结束-->

    <!-- 新增/修改用户弹窗开始 -->
    <el-dialog title="新增角色" v-model="data.dialogFormVisible" width="400" destroy-on-close align-center>
        <el-form ref="roleformRef" :model="data.roleForm" :rules="data.rules" label-width="80px" style="padding: 20px 30px 10px 20px">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="data.roleForm.roleName" autocomplete="off" style="width: 230px"/>
            </el-form-item>
            <el-form-item label="角色描述" prop="description">
                <el-input v-model="data.roleForm.description" autocomplete="off" style="width: 230px"/>
            </el-form-item>
            <el-form-item label="权限" prop="authority_name">
                <!-- 绑定roleForm，管理员选择后在roleadd方法中roleForm.auth_name将以参数的形式传递给后端进行权限的添加, 此处传递一个权限数组 -->
                <el-select  v-model="data.roleForm.authority_name" multiple placeholder="请分配权限" style="width: 230px">
                    <el-option v-for="item in auth_options" :key="item.authority_name" :label="item.auth_label" :value="item.authority_name"/>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="sava">保存</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 新增用户弹窗开始 -->



</template>

<script setup>
import {Delete, Search} from "@element-plus/icons-vue";
import {reactive, ref} from "vue"
import { markRaw } from 'vue'
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

// 数据
const data = reactive({
    role_name: null,
    tableData: [], // 角色数据列表
    pageNum: 1, //当前页面
    pageSize: 5, //页面数量
    total: 0,  //数据总数
    dialogFormVisible: false,
    roleForm: {
        authority_name: [], // 新增角色选择的权限数组
    }, //角色信息表单
    rules: {
        roleName: [
            { required: true, message: "请填写角色名称", trigger: 'change' },
            {max:15, message: "账号最多15位", trigger: 'blur'}
        ],
        description: [
            { required: true, message: "请填写角色描述", trigger: 'change' },
            { max: 40, message: '最多输入40位', trigger: 'blur' },
        ],
        authority_name: [
            { required: true, message: "请分配对应权限", trigger: 'change' },
        ],
    },
})

// 权限列表
let authorityName = ref('')
const options = [
    {authorityName: '用户基本权限', label: '用户基本权限',},
    {authorityName: '分类标签管理权限', label: '分类标签管理',},
    {authorityName: '消息管理权限', label: '消息管理',},
    {authorityName: '角色权限管理权限', label: '角色权限管理',},
    {authorityName: '用户管理权限', label: '用户管理',},
    {authorityName: '审核管理权限', label: '审核管理',},
]

// 角色查询
const roleload = () => {
    // 前后端数据查询
    request.get('/api/admin/selectRolePage', {
        params : {
            pageNum : data.pageNum,
            pageSize : data.pageSize,  //添加参数给后端实现分页
            role_name: data.role_name,
            authorityName: authorityName.value,
        }
    }).then(res => {
        if (res.code === "200") {
            data.tableData = res.data.list // 获取后端返回的所有用户信息
            data.total = res.data.total    // 后台数据总数
        } else {
            ElMessage.error(res.msg)
        }
    })
}
roleload()

// 表单绑定
const roleformRef = ref();
// 取消
const cancel = () => {
    data.dialogFormVisible = false
    data.roleForm = {}
    authority_name.value = null // 清理选择及数据，并打开弹窗
}
// 兼容 新增和修改
const sava = () => {
    data.roleForm.roleId ? editRole() : roleAdd()
}
// 新增用户的角色选择
let authority_name = ref([])
const auth_options = [
    {authority_name: '用户基本权限', auth_label: '用户基本权限',},
    {authority_name: '分类标签管理权限', auth_label: '分类标签管理权限',},
    {authority_name: '消息管理权限', auth_label: '消息管理权限',},
    {authority_name: '角色权限管理权限', auth_label: '角色权限管理权限',},
    {authority_name: '用户管理权限',auth_label: '用户管理权限',},
    {authority_name: '审核管理权限',auth_label: '审核管理权限',},
]
// 新增弹窗控制
const handleAdd = () => {
    data.dialogFormVisible = true
    data.roleForm = {}
    authority_name = [] // 清理选择及数据，并打开弹窗
}
// 修改角色方法
const roleAdd = () => {
    roleformRef.value.validate((valid) => {
        if (valid) {
            request.post('/api/admin/roleAdd',{
                role:data.roleForm,
                authorityNames: data.roleForm.authority_name,
            }).then(res => {
                if (res.code === "200")  {
                    ElMessage.success("角色添加成功")
                    roleload()
                    data.dialogFormVisible = false
                } else {
                    ElMessage.error(res.msg)
                }
            })
        }
    })
}
// 删除按钮
const deleteRole = (roleId) => {
    ElMessageBox.confirm('您确定删除此角色嘛 此操作不可逆转！请谨慎操作！', '删除确认', {
        type: 'warning',
        icon: markRaw(Delete),
    }).then(res => {
        request.delete('/api/admin/roleDel/' + roleId).then(res => {
            if (res.code === "200") {
                ElMessage.success("删除成功");
                roleload()
            } else {
                ElMessage.error(res.msg)
            }
        })
    }).catch(err => {})
}
// 修改弹窗
const handleEdit = (row) => {
    data.dialogFormVisible = true
    data.roleForm = JSON.parse(JSON.stringify(row));
    data.roleForm.authority_name = row.authorities.map(authority => authority.authorityName);  // 选项反选
}
// 修改角色方法
const editRole = () => {
    roleformRef.value.validate((valid) => {
        if (valid) {
            request.put('/api/admin/updateRole',{
                role:data.roleForm,
                authorityNames: data.roleForm.authority_name,
            }).then(res => {
                if (res.code === '200') {
                    ElMessage.success('修改用户成功')
                    roleload() //加载最新数据
                    data.dialogFormVisible = false // 关闭弹窗
                } else {
                    ElMessage.error(res.msg)
                }
            })
        }
    })
}

// 重置按钮
const reset = () => {
    data.role_name = null
    authorityName.value = null
    roleload()
}
</script>

<style scoped>
/*输入框聚焦效果*/
/*input:focus {*/
/*    outline: none;*/
/*    box-shadow: 0 0 0 3px rgba(51, 153, 255, 0.2); !* 蓝色光环效果 *!*/
/*}*/
</style>